import { aliOssSecurityToken } from "@/apis/file";
import AliOssSdk from "ali-oss";

// todo:目前sts每次调用重新获取
export const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

export const getAuth = () => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const { data } = await aliOssSecurityToken();
      resolve({
        region: "oss-cn-hangzhou",
        bucket: data.bucketName,
        accessKeyId: data.accessKeyId,
        accessKeySecret: data.accessKeySecret,
        stsToken: data.securityToken
      });
    } catch (err) {
      reject(err);
    }
  });
};
export const getClientOss = () => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const clientOss = await getAuth();
      const clientOssObj = new AliOssSdk({
        ...clientOss
      });
      resolve(clientOssObj);
    } catch (err) {
      reject(err);
    }
  });
};
export const getProgress = progress => {
  return Math.floor(progress * 100);
};

// 文件权限
export const setACL = async (ObjName, configObj) => {
  const client = await getClientOss();
  return await client.putACL(ObjName, configObj);
};

// 文件url
export const signatureUrl = async ObjName => {
  const client = await getClientOss();
  return await client.signatureUrl(`${ObjName}`);
};
